import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

/**
 * meta内容：
 * noLogin(false): 不需要登录就能访问，通过缓存判断是否登录，如果是老板娘登录的页面在未登录情况下直接跳到login页面
 * needLoading(false): 进入页面时loading，在页面通过this.$bus.$emit('ready/error')去解除loading
 * showNav(false): 显示底部导航
 */

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    meta: {
      noLogin: true,
      needLoading: true
    }
  },
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/Home.vue'),
    meta: {
      noLogin: true,
      showNav: true
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('@/views/order'),
    meta: {
      needLoading: true,
      showNav: true
    }
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('@/views/dashboard'),
    meta: {
      noLogin: true,
      showNav: true
    }
  },
  {
    path: '/dashboard2',
    name: 'dashboard2',
    component: () => import('@/views/dashboard/index2.vue'),
    meta: {
      noLogin: true,
      needLoading: true,
      showNav: true
    }
  },
  {
    path: '*',
    name: 'notFound',
    component: () => import('@/views/notFound'),
    meta: {
      noLogin: true
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const { isLogin } = store.state.login
  if (!isLogin) {
    // 未登录的情况下判断to的页面是否需要登录
    if (to.meta.noLogin) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 已登录的情况下判断to的页面是否为登录页
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  }
})

export default router
